package com.my.learn.thread.juc;

import java.util.concurrent.*;

/**
 * 主要用于并行计算中和 MapReduce 原理类似，都是把大的计算任务拆分成多个小任务并行计算。
 */
public class ForkJoinTest extends RecursiveTask<Integer> {

    private int threadNum = 10;
    private int first;
    private int last;

    public ForkJoinTest(int first, int last) {
        this.first = first;
        this.last = last;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinTest test = new ForkJoinTest(1, 999);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Future result = forkJoinPool.submit(test);
        System.out.println(result.get());
        int r = 0;
        for (int i = 0; i < 1000; i++) {
            r += i;
        }
        System.out.println(r);
    }

    @Override
    public Integer compute() {
        int result = 0;
        if (last - first <= threadNum) {
            for (int i = first; i <= last; i++) {
                result += i;
            }
        } else {
            int middle = (last + first) / 2;
            System.out.println("f:" + first + " l:" + last + " m:" + middle);
            ForkJoinTest leftForkJoinTest = new ForkJoinTest(first, middle);
            ForkJoinTest rightForkJoinTest = new ForkJoinTest(middle + 1, last);
            leftForkJoinTest.fork();
            rightForkJoinTest.fork();
            result = leftForkJoinTest.join() + rightForkJoinTest.join();
        }
        return result;
    }

}
